import {HttpErrorResponse, HttpInterceptorFn, HttpRequest} from '@angular/common/http';
import {catchError, Observable, throwError} from 'rxjs';
import {inject} from '@angular/core';
import {Router} from '@angular/router';
import {AuthService} from './auth.service';

const BASE_URL = ' http://localhost:3000/api'

export const appHttpInterceptor: HttpInterceptorFn = (req, next) => {
  const modifiedUrl = addAuthHeader(addBaseUrl(req))
  const router = inject(Router);
  const authService = inject(AuthService);
  return next(modifiedUrl).pipe(
    catchError((err) => {
      return handleError(err, router, authService)
    })
  );
};

function addAuthHeader(request: HttpRequest<unknown>): HttpRequest<unknown>{
  const token = localStorage.getItem('access_token');
  if (token && shouldAddAuthHeader(request.url)) {
    return request.clone({
      setHeaders: {
        'Authorization': `Bearer ${token}`,
      }
    });
  }
  return request
}

function addBaseUrl(request: HttpRequest<unknown>): HttpRequest<unknown> {
  if (request.url.startsWith('http://') || request.url.startsWith('https://')) {
    return request;
  }

  if (request.url.startsWith('assets/')) {
    return request;
  }

  const apiUrl = `${BASE_URL}${request.url.startsWith('/') ? '' : '/'}${request.url}`;

  return request.clone({
    url: apiUrl
  });
}

function shouldAddAuthHeader(url: string): boolean {
  const excludeUrls = [
    '/users/register',
    '/users/login',
  ];
  return !excludeUrls.some(excludeUrl => url.includes(excludeUrl));
}

function handleError(error: HttpErrorResponse, router: Router, authService: AuthService): Observable<never> {
  let errorMessage = '发生未知错误';

  switch (error.status) {
    case 400:
      errorMessage = error.error?.message || '请求参数错误';
      break;
    case 401:
      errorMessage = '未授权，请重新登录';
      authService.logout();
      router.navigate(['/login'])
      break;
    case 403:
      errorMessage = '没有权限访问此资源';
      break;
    case 404:
      errorMessage = '请求的资源不存在';
      break;
    case 500:
      errorMessage = '服务器内部错误';
      break;
    case 502:
      errorMessage = '网关错误';
      break;
    case 503:
      errorMessage = '服务暂时不可用';
      break;
    case 0:
      errorMessage = '网络连接失败，请检查网络设置';
      break;
    default:
      errorMessage = error.error?.message || `HTTP错误: ${error.status}`;
  }

  console.error('HTTP请求错误:', {
    status: error.status,
    message: errorMessage,
    url: error.url,
    error: error.error
  });

  // 显示错误消息（除了401错误，因为401会自动跳转到登录页）
  if (error.status !== 401) {
    // this.messageService.error(errorMessage);
  }

  // 返回用户友好的错误信息
  const userError = new HttpErrorResponse({
    error: {
      ...error.error,
      userMessage: errorMessage
    },
    headers: error.headers,
    status: error.status,
    statusText: error.statusText,
    url: error.url || undefined
  });

  return throwError(() => userError);
}
